package com.simple.cms.common.utils;


import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;


import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.security.Key;
import java.security.spec.AlgorithmParameterSpec;

public class DESUtils {

    private static final String DESKey = "iMovie#Token$2017";// 设置密钥，略去
    private static final byte[] DESIv = {0x12, 0x34, 0x56, 0x78, (byte) 0x90, (byte) 0xAB, (byte) 0xCD, (byte) 0xEF};// 设置向量，略去


    public static String encode(String data) {
        try {
            DESKeySpec keySpec = new DESKeySpec(DESKey.getBytes("UTF-8"));// 设置密钥参数
            AlgorithmParameterSpec iv = new IvParameterSpec(DESIv);// 设置向量
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");// 获得密钥工厂
            Key key = keyFactory.generateSecret(keySpec);// 得到密钥对象
            Cipher enCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");// 得到加密对象Cipher
            enCipher.init(Cipher.ENCRYPT_MODE, key, iv);// 设置工作模式为加密模式，给出密钥和向量
            byte[] pasByte = enCipher.doFinal(data.getBytes("utf-8"));

            Base64 base64 = new Base64();
            return base64.encodeToString(pasByte);
            //return DataSwitch.bytesToHexString(pasByte);
        } catch (Exception e) {
            return StringUtils.EMPTY;
        }
    }

    public static String decode(String data) throws Exception {
        try {
            DESKeySpec keySpec = new DESKeySpec(DESKey.getBytes("UTF-8"));// 设置密钥参数
            AlgorithmParameterSpec iv = new IvParameterSpec(DESIv);// 设置向量
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");// 获得密钥工厂
            Key key = keyFactory.generateSecret(keySpec);// 得到密钥对象
            Cipher deCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
            deCipher.init(Cipher.DECRYPT_MODE, key, iv);

            Base64 base64 = new Base64();
            byte[] pasByte = deCipher.doFinal(base64.decode(data));
            return new String(pasByte, "UTF-8");
            //     return new String(deCipher.doFinal(DataSwitch.hexStringToByte(data)), "utf-8");

        } catch (Exception e) {
            return StringUtils.EMPTY;
        }
    }


    public static void main(String[] args) {
        try {
            String test = "10000002";
            System.out.println("加密前的字符：" + test);
            System.out.println("加密后的字符：" + DESUtils.encode(test));
            System.out.println("解密后的字符：" + DESUtils.decode(DESUtils.encode(test)));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
